
import json
import urllib
import urllib.request
import urllib.error
import time
from functools import wraps
import sys
import ssl
import random
import string


"""使用的是Python3"""
PY2 = False
PY3 = False
if sys.version_info[0] == 2:
    PY2 = True
    print("要求使用Python3")
    sys.exit()
elif sys.version_info[0] == 2:
    PY3 = True


from .http_multipart import http_multipart

# ssl._create_default_https_context = ssl._create_unverified_context

# host_url = 'http://192.168.20.248:5007'
host_url = 'http://127.0.0.1:5001/chess'
# host_url = 'http://101.37.28.76/chess'
# host_url = 'https://www.medtrum.com:8443'

test_url = host_url + '/api/v2.0/test'
create_game_url = host_url + '/api/v2.0/create_game'
chess_game_process_url = host_url + '/api/v2.0/chess_game_process'
load_chess_game_url = host_url + '/api/v2.0/load_chess_game'
get_match_history_url = host_url + '/api/v2.0/get_match_history'
cal_machine_move_url = host_url + '/api/v2.0/cal_machine_move'
user_register_url = host_url + '/api/v2.0/user/register'
user_login_url = host_url + '/api/v2.0/user/login'
port_test_url = host_url + '/api/v2.0/test'
game_enter_district_url = host_url + '/api/v2.0/game/enter_district'

context = {}


def login_v2(args):
    # data = urllib.urlencode(args)
    data=json.dumps(args, ensure_ascii=False).encode('utf8')
    req = urllib.request.Request(login_url, data, {'Content-Type':'application/json;charset=UTF-8'})
    try:
        rsp = urllib.request.urlopen(req)
        # print 'rsp:', dir(rsp), rsp.headers, type(rsp)
        # print 'cookie:', rsp.headers.get('Set-Cookie')
        cookie = rsp.headers.get('Set-Cookie')
        rv = rsp.read()
    except Exception as e:
        print('login_v2 error:', e)
        return
    print('login:', rv)
    with open('login.txt', 'wb') as fo:
        fo.write(rv)
    rv = json.loads(rv, encoding='utf8')
    # if 'OK'==rv['res']:
    if 0 == rv['error']:
        print('cookie:', cookie)
        context['cookie'] = cookie
    return rv


def show_time(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        # if not can_run:
        #     return "Function will not run"
        t1 = time.time()
        rv = f(*args, **kwargs)
        t2 = time.time()
        print('http use time:', t2 - t1)
        return rv

    return decorated


@show_time
def http_post_v2(req_url, args, **opt):
    show_header = opt.get('show_header', False)
    OTAToken = opt.get('OTAToken', False)
    pass

    data = json.dumps(args, ensure_ascii=False)

    data = bytes(data, 'utf8')

    print('data', data, type(data))

    #
    header = {
        'Content-Type': 'application/json;charset=UTF-8',
        # 'Cookie': context.get('cookie'),
        # 'Token': 'C0NNqtiOd2BWElrR8W4l8c2t5O1NaX0D2c7cgGfFAyYykYTtgh6KUJTwA8WBSBkd'
    }
    #
    if context.get('cookie'):
        header['Cookie'] = context.get('cookie')

    if OTAToken:
        header['OTAToken'] = OTAToken
    #
    req = urllib.request.Request(req_url, data, headers=header)
    # rsp = urllib2.urlopen(req,timeout=0.1)   # for test timeout arg
    rsp = urllib.request.urlopen(req)

    rv = rsp.read()

    cookie = rsp.headers.get('Set-Cookie')

    if cookie:
        context['cookie'] = cookie

    print('cookie:', cookie)

    if show_header:
        print('header:', rsp.headers)
    rv_json = json.loads(rv)

    with open('rv.txt', 'wb') as fo:
        fo.write(rv)

    return rv_json


def http_get(req_url, args=None, **opt):
    show_header = opt.get('show_header', False)
    pass

    if args:
        data = urllib.urlencode(args)
        req_url += '?' + data
    # else:
    #    data = None
    print('req_url:', req_url)
    req = urllib.request.Request(req_url, None, {'Cookie': context.get('cookie')})

    try:
        rsp = urllib.request.urlopen(req)
        # rsp.readline()
        rv = rsp.read()
    except Exception as e:
        print('============================')
        print('http_get error', e, e.message)
        return

    if show_header:
        print('header:', rsp.headers)

    # try:
    #     pass
    #     # return json.loads(rv, encoding='utf8')
    # except Exception as e:
    #     pass
    with open('rv.txt', 'wb') as fo:
        fo.write(rv)

    return rv


def test_api_test():
    rv = http_post_v2(test_url, {
        'test':'123'
    })
    print('rv:', rv)


def test_api_create_game():
    rv = http_post_v2(create_game_url, {
        'test': '123'
    })
    print('rv:', rv)


def test_api_chess_game_process():
    move_set = (
       # ("BP1", (2, 3), (5, 3)),
       # ("RP1", (2, 3), (5, 3)),
       ("BM1", (2, 1), (3, 3)),
       ("RB4", (7, 4), (7, 5)),
    )
    for move in move_set:
        rv = http_post_v2(chess_game_process_url, {
            'match_id': 1,
            'move': move
        })
        print('rv:', move, rv)


def test_api_load_chess_game():
    rv = http_post_v2(load_chess_game_url, {
        'match_id': 1
    })
    print('rv:', rv)


def test_api_get_match_history():
    rv = api_login({
        'username': 'aa3',
        'password': '1234'
    })

    rv = http_post_v2(get_match_history_url, {
        'match_id': 20
    })
    print('rv:', rv)


def test_api_cal_machine_move():
    rv = api_login({
        'username': 'aa3',
        'password': '1234'
    })

    rv = http_post_v2(cal_machine_move_url, {
        'match_id': 20,
        'seq': 1,
    })
    print('rv:', rv)


def random_digits_letters(size=16):
    s = map(lambda x: random.choice(string.digits+string.ascii_letters), range(size))
    return ''.join(s)


def test_api_user_register():
    rv = http_post_v2(user_register_url, {
        'username': 'aa3',
        'password': '1234'
    })
    print('rv:', rv)


def api_login(params):
    rv = http_post_v2(user_login_url, params)
    # print('rv:', rv)
    return rv


def test_api_user_login():
    rv = http_post_v2(user_login_url, {
        'username': 'aa2',
        'password': '1234'
    })
    print('rv:', rv)


def test_api_port_test():
    # rv = api_login({
    #     'username': 'aa2',
    #     'password': '1234'
    # })

    rv = http_post_v2(port_test_url, {
        'test': '123'
    })
    print('rv:', rv)


def test_api_game_enter_district():
    if True:
        rv = api_login({
            'username': 'aa2',
            'password': '1234'
        })
    else:
        rv = api_login({
            'username': 'aa3',
            'password': '1234'
        })
    print('login rv:', rv)
    rv = http_post_v2(game_enter_district_url, {
        'test': '123'
    })
    print('rv:', rv)


def test_temp():
    key = random_digits_letters(16)
    print('key:', key)


def test_obj_copy():
    from app.rule import ChessGame
    from copy import copy, deepcopy

    game = ChessGame()
    # 深拷贝和浅拷贝。
    game2 = deepcopy(game)
    game3 = copy(game)
    print(game, game2)
    game.step(['RP1', [2, 3], [3, 3]])
    game.print_status()
    game2.print_status()


def test_machine_move():
    from app.machine import machine_move

    machine_move(3, 'R')


def start():
    pass
    test_api_test()
    # test_api_create_game()
    # test_api_chess_game_process()
    # test_api_load_chess_game()
    # test_api_get_match_history()
    # test_api_cal_machine_move()
    # test_api_user_register()
    # test_api_user_login()
    # test_api_port_test()
    # test_temp()
    # test_api_game_enter_district()
    # test_obj_copy()
    # test_machine_move()


